package net.mysoft.framework.i18n;

import java.util.Locale;
import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.I18nInterceptor;
import com.opensymphony.xwork2.util.LocalizedTextUtil;

/**
 * i18n拦截器
 * 
 * @author liuyang
 * 
 */
public class LanguageInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Locale locale = null;
		// 获取request的参数列表
		Map<String, Object> params = invocation.getInvocationContext().getParameters();
		// 获取session
		Map<String, Object> session = invocation.getInvocationContext().getSession();
		// 获取request中request_locale参数值
		Object requested_locale = findLocaleParameter(params,I18nInterceptor.DEFAULT_PARAMETER);
		// 如果request中request_locale参数值为null，则获取request_only_locale参数值
		if (requested_locale == null) {
			// 如果request中request_only_locale参数值为null，则从session中获取WW_TRANS_I18N_LOCALE值，该值是struts2
			// 框架中的i18n拦截器根据request的request_locale参数值设置的语言环境
			if (requested_locale == null) {
				requested_locale = session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE);
				// 如果session中不存在WW_TRANS_I18N_LOCALE值，则获取ActionContext的语言环境
				if (requested_locale == null) {
					requested_locale = invocation.getInvocationContext().getLocale();
				}
			}
		}
		// 如果requested_locale为null，则将locale设置为国际化资源文件(config.properties.language)中配置的(warning.language.default)默认语言环境;
		// 如果requested_locale类型为Locale，则直接赋值给locale;
		// 如果上述两项都不匹配，则根据requested_locale初始化一个Locale对象
		locale = (requested_locale instanceof Locale) ? (Locale) requested_locale : (requested_locale != null ? LocalizedTextUtil.localeFromString
				(requested_locale.toString(),Locales.getDefaultLocale()): Locales.getDefaultLocale());
		// 如果国际化资源文件中配置的语言环境不包含上述获取的语言环境，则将locale赋值为国际化资源文件中配置的默认语言环境
		if (!Locales.getLocales().containsValue(locale)) {
			locale = Locales.getDefaultLocale(); 
		}
		// 设置ActionContext的语言环境
		session.put(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE, locale);
		invocation.getInvocationContext().setLocale(locale);
		
		return invocation.invoke();
	}

	/**
	 * 从Map集合中获取指定元素的值
	 * 
	 * @param params
	 * @param parameterName
	 * @return
	 */
	private Object findLocaleParameter(Map<String, Object> params,
			String parameterName) {
		Object requested_locale = params.get(parameterName);
		if (requested_locale != null && requested_locale.getClass().isArray()
				&& ((Object[]) requested_locale).length == 1) {
			requested_locale = ((Object[]) requested_locale)[0];
		}
		return requested_locale;
	}

}
